var express = require('express');
var router = express.Router();

const sql = require("../sql/sql");
const search = require("../sql/search");
const tools = require("../tools/index");
const uuid = require('node-uuid');

router.get('/',function(req,res,next){
    res.send("这是一个历史记录接口");
})

/**
* @apiGroup 历史搜索模块
* @api {get} /search/show 获取历史搜索
* @apiVersion 0.0.0
* @apiDescription 获取历史搜索
* @apiParam {string} userId 用户的唯一Id
* @apiSuccess {number} state 请求状态
* @apiSuccess {string} title 请求说明
* @apiSuccess {json} data 请求说明
* @apiSuccessExample {json} Success-Response:
res.send({
    stete:200,
    title:"获取记录成功",
    data:data
})
* @apiSampleRequest http://localhost:3000/api/search/show
*/


router.get('/show',function(req,res,next){
    const {userId} = req.query;
    tools.verify(req).then(()=>{
        sql.sort(search,{userId},{_id:0,__v:0},{time:-1}).then((data)=>{
            res.send({
                state:200,
                title:'获取历史记录成功',
                data:data
            })
        })
    }).catch(err=>{
        res.send({
            state:300,
            title:"登录失效"
        })
    })
})

/**
* @apiGroup 历史搜索模块
* @api {post} /search/add 添加历史记录
* @apiVersion 0.0.0
* @apiDescription 添加历史记录
* @apiParam {string} userId 用户的唯一Id
* @apiParam {string} searchText 搜索关键字
* @apiSuccess {number} state 请求状态
* @apiSuccess {string} title 请求说明
* @apiSuccess {json} data 请求说明
* @apiSuccessExample {json} Success-Response:
res.send({
    stete:200,
    title:"请求商品品牌成功",
    data:[{},{},{}..]
})
* @apiSampleRequest http://localhost:3000/api/search/add
*/

router.post("/add",function(req,res,next){
    const {userId,searchText} = req.body;
    tools.verify(req).then(()=>{
        sql.insert(search,{
            userId,
            searthText:searchText,
            searchId:"search"+uuid(),
            time:Date.now()
        }).then(()=>{
            res.send({
                state:200,
                title:'添加历史记录成功'
            })
        })
    }).catch(err=>{
        res.send({
            state:300,
            title:"登录失效"
        })
    })
})

/**
* @apiGroup 历史搜索模块
* @api {post} /search/del 删除历史记录
* @apiVersion 0.0.0
* @apiDescription 删除历史记录
* @apiParam {string} userId 用户的唯一Id
* @apiParam {string} searchId 历史记录唯一Id
* @apiSuccess {number} state 请求状态
* @apiSuccess {string} title 请求说明
* @apiSuccess {json} data 请求说明
* @apiSuccessExample {json} Success-Response:
res.send({
    stete:200,
    title:"删除历史记录成功",
})
* @apiSampleRequest http://localhost:3000/api/search/del
*/

router.post("/del",function(req,res,next){
    const {userId,searchId} = req.body;
    tools.verify(req).then(()=>{
        sql.delete(search,{userId,searchId}).then(()=>{
            res.send({
                state:200,
                title:'删除历史记录成功'
            })
        })
    }).catch(err=>{
        res.send({
            state:300,
            title:"登录失效"
        })
    })
})


module.exports = router;